//
//  HandleData.m
//  MyProject
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "HandleData.h"
#import <AFHTTPSessionManager.h>
@implementation HandleData

+ (void)handleDataWithUrl:(NSString *)url completion:(void (^)(id data))block
{
    // WiFi边上的 菊花
    UIApplication *application = [UIApplication sharedApplication];
    application.networkActivityIndicatorVisible = YES;
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"application/json",@"text/javascript",@"text/html", nil];
    
    NSString *strPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%lu.aa",strPath,(unsigned long)[url hash]]; // 存入本地的地址
    
    /*
     *  @param operation      网络请求成功
     *
     *
     *  @return 写入本地
     */
    
    [session GET:url parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        // 将AGNetworking 解析结果转换成data
        NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
        // 返回数据
        block(responseObject);
        [data writeToFile:path atomically:YES];
        application.networkActivityIndicatorVisible = NO;
    }
     /*
      *  网络请求失败 读取本地数据
      */
         failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
             
             NSData *data = [NSData dataWithContentsOfFile:path];
             if (data != nil) {
                 id data1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                 block(data1);
             }
             application.networkActivityIndicatorVisible = NO;
         }];
}


@end
